package com.cyh.forum.controller;

import com.cyh.forum.common.AppResult;
import com.cyh.forum.common.ResultCode;
import com.cyh.forum.config.AppConfig;
import com.cyh.forum.exception.ApplicationException;
import com.cyh.forum.model.Article;
import com.cyh.forum.model.Board;
import com.cyh.forum.model.User;
import com.cyh.forum.services.IArticleService;
import com.cyh.forum.services.IBoradService;
import com.sun.net.httpserver.HttpsServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.spec.DSAGenParameterSpec;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IBoradService iBoradService;
    @Resource
    private IArticleService iArticleService;

    @ApiOperation("发布帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("版块ID") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("⽂章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖⼦内容") @RequestParam("content") @NonNull String content){
        //  通过session获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //  校验用户是否被禁言
        if (user.getState() == 1){
            //  打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //  校验版块是否被删除
        Board board = iBoradService.selectByPrimaryKey(boardId);
        if (board.getDeleteState() == 1 || board.getState() == 1 || board == null){
            //  版块状态异常
            //  打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //  设置传入值给 article对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setTitle(title);
        article.setContent(content);

        //  调用service 写入article对象
        iArticleService.create(article);

        //  返回结果
        return AppResult.success();
    }


    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("版块id") @RequestParam(value = "boardId",required = false) Long boardId){

        List<Article> articles;
        //  先判断 boardID 是空还是非空
        if (boardId == null){
            articles = iArticleService.selectAll();
        }else {
            articles = iArticleService.selectByBoardId(boardId);
        }

        //  判断是否为空
        if (articles == null) {
            //  如果结果集为空,创建一个空的集合返回
            articles = new ArrayList<>();
        }
        //  响应结果
        return AppResult.success(articles);
    }

    @ApiOperation("根据ID查询帖子详情")
    @GetMapping("/Details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id){
        //  通过session获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //  调用service层获取帖子详情
        Article article = iArticleService.selectDetailById(id);
        //  判断是否为当前用户
        if (user.getId() == article.getUserId()){
            article.setOwn(true);
        }
        return AppResult.success(article);
    }


    @ApiOperation("编辑帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子正文") @RequestParam("content") @NonNull String content){
        //  获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //  获取帖子原始数据
        Article article = iArticleService.selectById(id);
        //  校验用户是否被禁言
        if (user.getState() != 0){
            //  打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //  校验当前用户是否为作者
        if (user.getId() != article.getUserId()){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //  校验帖子是否存在
        if (article == null){
            //  打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //  校验帖子状态是否异常
        if (article.getState() != 0 || article.getDeleteState() != 0){
            //  打印日志
            log.warn("articleID = " + id + "article state = " + article.getState() + "article DeleteState = " + article.getDeleteState());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //  执行更新操作  调用service层
        iArticleService.modify(id,title,content);
        //  打印执行成功的日志
        //  通过调用 MessageFormat.format() 方法并传入模板字符串和实际值，可以将占位符替换为具体的值，生成最终的消息字符串。
        log.info(MessageFormat.format("帖⼦修改成功. id = {0}, user id = {1}, 原标题 = {2}, 新标题 = {3}",
                id, user.getId(), article.getTitle(), title));
        //  返回结果
        return AppResult.success();
    }

    @ApiOperation("点赞操作")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(@ApiParam("帖子ID") @RequestParam("id") @NonNull Long id){
        //  参数校验
        if (id == null || id <= 0){
            //  打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //  调用service层
        iArticleService.thumbsUpById(id);
        //  返回结果
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @GetMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子ID") @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //  获取帖子的原始数据
        Article article = iArticleService.selectById(id);
        //  1.校验当前用户是否为作者
        if (user.getId() != article.getUserId()){
            //  打印日志
            log.warn(ResultCode.FAILED_USER_NOT_AUTHOR.toString());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_USER_NOT_AUTHOR);
        }
        //  2.校验帖子是否存在
        if (article == null || article.getDeleteState() == 1){
            //  打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //  调用service层
        iArticleService.deleteById(id);
        //  返回结果
        return AppResult.success();
    }


    @ApiOperation("显示用户发表的帖子")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam("用户ID") @RequestParam(value = "userId",required = false) Long userId){
        //  如果userId为空,查询当前用户自己的帖子列表
        if(userId == null){
            val session = request.getSession(false);
            User user =(User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //  调用service层
        val articles = iArticleService.selectByUserId(userId);
        return AppResult.success(articles);

    }



}
